package client;

import commun.Compte;
import javax.swing.JOptionPane;

public final class IHM extends javax.swing.JFrame {

    ClientService cs = new ClientService();
    private boolean typeFonctionIdentifier; // Visible sur IHM coté utilisateur : true -> Se connecter et false -> Se déconnecter    

    public IHM() {
        initComponents();
        this.modeDeconnecter();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextFieldNom = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldMotDePasse = new javax.swing.JTextField();
        jButtonIdentifier = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jLabelSommeAvecSymbole = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldMontant = new javax.swing.JTextField();
        jButtonAjouterMontant = new javax.swing.JButton();
        jButtonRetirer = new javax.swing.JButton();
        jButtonFermerLeCompte = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jButtonActualiserSolde = new javax.swing.JButton();
        jButtonNouveauCompte = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Identifiant : ");

        jLabel2.setText("Mot de passe : ");

        jTextFieldMotDePasse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldMotDePasseActionPerformed(evt);
            }
        });

        jButtonIdentifier.setText("Se connecter");
        jButtonIdentifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonIdentifierActionPerformed(evt);
            }
        });

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Solde du compte : ");
        jLabel3.setFocusable(false);
        jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jLabelSommeAvecSymbole.setText("€");

        jLabel5.setText("Montant : ");

        jButtonAjouterMontant.setText("Ajouter");
        jButtonAjouterMontant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterMontantActionPerformed(evt);
            }
        });

        jButtonRetirer.setText("Retirer");
        jButtonRetirer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRetirerActionPerformed(evt);
            }
        });

        jButtonFermerLeCompte.setText("Fermer le compte");
        jButtonFermerLeCompte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFermerLeCompteActionPerformed(evt);
            }
        });

        jButtonActualiserSolde.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButtonActualiserSolde.setText("Actualiser solde");
        jButtonActualiserSolde.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonActualiserSoldeActionPerformed(evt);
            }
        });

        jButtonNouveauCompte.setText("Créer un compte");
        jButtonNouveauCompte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNouveauCompteActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel4.setText("RMI Banque");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator3)
            .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonFermerLeCompte)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldMontant, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonAjouterMontant)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRetirer))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldMotDePasse, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButtonNouveauCompte, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonIdentifier, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelSommeAvecSymbole)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButtonActualiserSolde, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(138, 138, 138))
            .addGroup(layout.createSequentialGroup()
                .addGap(181, 181, 181)
                .addComponent(jLabel4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonNouveauCompte))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldMotDePasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonIdentifier))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabelSommeAvecSymbole))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addComponent(jButtonActualiserSolde, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonFermerLeCompte)
                    .addComponent(jButtonAjouterMontant)
                    .addComponent(jButtonRetirer)
                    .addComponent(jTextFieldMontant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAjouterMontantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterMontantActionPerformed
        // Ajouter montant                                
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        int sommeAAjouter = this.lireMontantDuChamp();
        
            if(sommeAAjouter != 0){
                Compte compte = new Compte(nom, motDePasse);
                cs.deposer(sommeAAjouter, compte);

                this.actualiserSoldeCompte();

                JOptionPane.showMessageDialog(this, "La somme de : " + sommeAAjouter + " € a été ajoutée du compte " + compte.getID(), "Information", JOptionPane.INFORMATION_MESSAGE);
            }
            
        jTextFieldMontant.setText("");
    }//GEN-LAST:event_jButtonAjouterMontantActionPerformed

    private void jButtonIdentifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIdentifierActionPerformed
        // Bouton d'identification, gère la connexion et la déconnexion
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        if (typeFonctionIdentifier == true) {
            Compte compte = cs.verifie(nom, motDePasse);
            if (compte != null) {
                boolean b2 = cs.connecter(nom);
                if (b2 == true) {
                    this.modeConnecter();
                    this.actualiserSoldeCompte();
                } else {
                    JOptionPane.showMessageDialog(this, "Une personne est déjà connecté sur votre compte", "Erreur", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Erreur d'authentification, ou compte inconnu", "Erreur", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            jTextFieldNom.setText("");
            jTextFieldMotDePasse.setText("");
            this.seDeconnecter(nom);
        }
    }//GEN-LAST:event_jButtonIdentifierActionPerformed

    private void jButtonNouveauCompteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNouveauCompteActionPerformed
        // Bouton pour ajouter un nouveau compte
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        if (!"".equals(nom) && !"".equals(motDePasse)) {
            cs.ouvrirCompte(nom, motDePasse);
            jTextFieldNom.setText("");
            jTextFieldMotDePasse.setText("");
            JOptionPane.showMessageDialog(this, "Le nouveau compte a été crée, sauf si il y a une erreur sur le serveur", "Information", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Les champs Nom et Mot De Passe sont vides", "Erreur", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonNouveauCompteActionPerformed

    private void jButtonRetirerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRetirerActionPerformed
        // Retirer montant                                     
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        int sommeARetirer = this.lireMontantDuChamp();

            if(sommeARetirer != 0){
                Compte compte = new Compte(nom, motDePasse);
                cs.retirer(sommeARetirer, compte);

                this.actualiserSoldeCompte();

                JOptionPane.showMessageDialog(this, "La somme de : " + sommeARetirer + " € a été retirée du compte " + compte.getID(), "Information", JOptionPane.INFORMATION_MESSAGE);
            }
            
        jTextFieldMontant.setText("");
    }//GEN-LAST:event_jButtonRetirerActionPerformed

    private void jButtonFermerLeCompteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFermerLeCompteActionPerformed
        // Fermer compte
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        int soldeDeRetour = cs.fermerCompte(nom, motDePasse);
        JOptionPane.showMessageDialog(this, "Le solde restant de votre ancien compte est de " + soldeDeRetour + " €", "Information", JOptionPane.INFORMATION_MESSAGE);

        this.seDeconnecter(nom);
    }//GEN-LAST:event_jButtonFermerLeCompteActionPerformed

    private void jButtonActualiserSoldeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonActualiserSoldeActionPerformed
        // Actualiser solde
        this.actualiserSoldeCompte();
    }//GEN-LAST:event_jButtonActualiserSoldeActionPerformed

    private void jTextFieldMotDePasseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldMotDePasseActionPerformed
        // Rien à mettre
    }//GEN-LAST:event_jTextFieldMotDePasseActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // Si on ferme la fenetre, pour déconnecter l'utilisateur
        String nom = jTextFieldNom.getText();

        if (typeFonctionIdentifier == false) {
            this.seDeconnecter(nom);
        }
    }//GEN-LAST:event_formWindowClosing

    private void seDeconnecter(String nom) {
        cs.deconnecter(nom);
        this.modeDeconnecter();
        JOptionPane.showMessageDialog(this, "Vous êtes déconnecté", "Information", JOptionPane.INFORMATION_MESSAGE);
    }

    private void actualiserSoldeCompte() {
        String nom = jTextFieldNom.getText();
        String motDePasse = jTextFieldMotDePasse.getText();

        Compte compte = new Compte(nom, motDePasse);

        int soldeCompte = cs.voirSolde(compte);
        this.setMontantIHM(soldeCompte);
    }

    private void modeConnecter() {
        jTextFieldNom.setEnabled(false);
        jTextFieldMotDePasse.setEnabled(false);
        jLabelSommeAvecSymbole.setText("€");
        jButtonIdentifier.setText("Se déconnecter");
        jTextFieldMontant.setEnabled(true);
        jButtonNouveauCompte.setEnabled(false);
        jButtonActualiserSolde.setEnabled(true);
        jButtonFermerLeCompte.setEnabled(true);
        jButtonAjouterMontant.setEnabled(true);
        jButtonRetirer.setEnabled(true);
        typeFonctionIdentifier = false;
    }

    private void modeDeconnecter() {
        jTextFieldNom.setEnabled(true);
        jTextFieldMotDePasse.setEnabled(true);
        jLabelSommeAvecSymbole.setText("€");
        jButtonIdentifier.setText("Se connecter");
        jTextFieldMontant.setEnabled(false);
        jButtonNouveauCompte.setEnabled(true);
        jButtonActualiserSolde.setEnabled(false);
        jButtonFermerLeCompte.setEnabled(false);
        jButtonAjouterMontant.setEnabled(false);
        jButtonRetirer.setEnabled(false);
        typeFonctionIdentifier = true;
    }

    private int lireMontantDuChamp() {
        int value = 0;

        String valueS = jTextFieldMontant.getText();
        
            try {
                value = Integer.parseInt(valueS);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Le montant inscrit n'est pas un nombre entier", "Erreur", JOptionPane.ERROR_MESSAGE);
                value = 0;
            }
        return value;
    }

    private void setMontantIHM(int montant) {
        jLabelSommeAvecSymbole.setText(String.valueOf(montant + " €"));
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new IHM().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonActualiserSolde;
    private javax.swing.JButton jButtonAjouterMontant;
    private javax.swing.JButton jButtonFermerLeCompte;
    private javax.swing.JButton jButtonIdentifier;
    private javax.swing.JButton jButtonNouveauCompte;
    private javax.swing.JButton jButtonRetirer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelSommeAvecSymbole;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTextField jTextFieldMontant;
    private javax.swing.JTextField jTextFieldMotDePasse;
    private javax.swing.JTextField jTextFieldNom;
    // End of variables declaration//GEN-END:variables
}
